/**
 * 常用JS变量:
 * agentEvent = 代理模式下自动点击模块
 * acEvent= 无障碍模式下自动点击模块
 * device = 设备信息模块
 * file = 文件处理模块
 * http = HTTP网络请求模块
 * shell = shell命令模块
 * thread= 多线程模块
 * image = 图色查找模块
 * utils= 工具类模块
 * global = 全局快捷方式模块
 * 常用java变量：
 *  context : Android的Context对象
 *  javaLoader : java的类加载器对象
 * 导入Java类或者包：
 *  importClass(类名) = 导入java类
 *      例如: importClass(java.io.File) 导入java的 File 类
 *  importPackage(包名) =导入java包名下的所有类
 *      例如: importPackage(java.util) 导入java.util下的类
 *
 */
let taskType = ["综合", "最热", "最新"];//任务类型
let noteType = ["全部", "视频", "图文"];//笔记类型
let splideTimes = 5;//下滑次数
let xhsAppName = "小红书";
const xhsPkg = "com.xingin.xhs";
const chat_Path = "/sdcard/Pictures/xhs_ec_config/privateMessage/chat/";
const keyword_path = "/sdcard/Pictures/xhs_ec_config/privateMessage/keyword.txt";
const jumpLink_path = "/sdcard/Pictures/xhs_ec_config/privateMessage/jumpLink.txt";
const userinfo_Path = "/sdcard/Pictures/xhs_ec_config/privateMessage/userInfo.txt";
const config_Path = "/sdcard/Pictures/xhs_ec_config/privateMessage/config.txt";
const xhs_message_jumpLink = "/sdcard/Pictures/xhs_ec_config/privateMessage/xhs_message_jumpLink.txt";//私信跳转链接id
const xhs_message_user = "/sdcard/Pictures/xhs_ec_config/privateMessage/xhs_message_user.txt";//私信跳转链接id
const home_url = "xhsdiscover://home/";
const search_page_viewId = "com.xingin.xhs:id/bux";//搜索后的可选笔记id
const xhs_user_home = "/sdcard/Pictures/xhs_ec_config/privateMessage/user_home.txt";//用户主页
const userId_path = "/sdcard/Pictures/xhs_ec_config/privateMessage/xhs_message_user.txt";//用户id
const sentMessCountPath = "/sdcard/Pictures/xhs_ec_config/privateMessage/count.txt";
const logPath = "/sdcard/Pictures/xhs_ec_config/privateMessage/log";
const page_count = "/sdcard/Pictures/xhs_ec_config/privateMessage/pageSum.txt";//私信跳转链接id
let airSwitchSize = 0;
let sentMessageSuccess_count = 0;//私信成功统计
let isUsefulAccount = 1;
let oneUserSendCount = 0;//单个用户私信统计，不管成功预付，累计私信2次，两次后删除当前私信链接
let pageCount = 0;
let fileCount = 0;
const enumId = {//小红书版本6.95
    xxmj_switchEnvrion: "zpp.wjy.xxsq:id/iv_envlist",//切换环境按钮
    xxmj_switchNextOne: "zpp.wjy.xxsq:id/btn_next",//切换下一个环境
    xxmj_remarkId: "zpp.wjy.xxsq:id/iv_rename",//xx抹机神奇备注
    xxmj_rename_InputId: "zpp.wjy.xxsq:id/editText",//xx抹机重命名输入框
    xxmj_rename_save: "android:id/button1",//备注重命名保存
    xxmj_currentIcon: "zpp.wjy.xxsq:id/iv_icon",//当前左上角app图标id
    xxmj_pkgName: "zpp.wjy.xxsq",//xx抹机包名
    xxmj_createNew: "zpp.wjy.xxsq:id/tv_new",//创建新环境

    huaweiPhone_airModeBut: "com.android.settings:id/switchWidget",//华为手机飞行模式按键id
    huaweiPhone_settingPage: "com.android.settings:id/content_frame",//华为手机设置外框id

    xhs_tackingPictures: "com.xingin.xhs:id/ak0",//拍照关闭
    xhsWarnTips: "com.xingin.xhs:id/cjy",//小红书温馨提示
    xhsWarnTips_agreeBut: "com.xingin.xhs:id/bkw",//小红书温馨提示同意按钮
    wifiTips: "com.xingin.xhs:id/a69",//视频笔记当中的wifi提示
    phoneLogin: "com.xingin.xhs:id/brh",//登录页面手机登录框
    wxLogin: "com.xingin.xhs:id/bx6",//微信登录框
    lognThisAccount: "com.xingin.xhs:id/bip",
    newVersion: "com.xingin.xhs:id/abx",//最新版本发布提示框
    newVersionExit: "com.xingin.xhs:id/abw",//最新版本发布取消叉叉框
    wxLoginThisAcount: "com.xingin.xhs:id/cob",//微信登录被顶，登录此账号
    otherAcountLogin: "com.xingin.xhs:id/z5",//其他账号登录
    homePage_noteParent: "com.xingin.xhs:id/bpu",//首页笔记父节点
    homePage_noteView: "com.xingin.xhs:id/b87",//首页图片
    choseHobby_title: "com.xingin.xhs:id/bwa",//选择爱好页面标题---文字好久不见
    choseHobby_jump: "com.xingin.xhs:id/bly",//选择爱好页面，跳过
    xhsAccessSpace: "com.xingin.xhs:id/djl",//是否允许小红书访问存储空间
    xhsAccessSpace_allowBut: "com.xingin.xhs:id/ccu",//允许按钮
    xhsAccessMedia: "com.android.packageinstaller:id/permission_message",//是否允许小红书访问手机相册媒体
    xhsAccessMedia_allowBut: "com.android.packageinstaller:id/permission_allow_button",//允许按钮

    searchResult_noteView: "com.xingin.xhs:id/ca7",//搜索页面笔记图片框
    searchResult_NoteParent: "com.xingin.xhs:id/bux",//关键字搜索笔记父选框
    searchClickIcon: "com.xingin.xhs:id/d01",//搜索放大镜
    searchInput: "com.xingin.xhs:id/bv_",//搜搜输入框
    searchClickBut: "com.xingin.xhs:id/bvd",//搜索点击按钮
    searchResult_new: "com.xingin.xhs:id/d5z",//最新搜索
    searchResult_hot: "com.xingin.xhs:id/d5y",//最热搜索
    searchResult_video: "com.xingin.xhs:id/an_",//搜索视频
    searchResult_pic: "com.xingin.xhs:id/amr",//搜索图文
    searchResult_user_xhsId: "com.xingin.xhs:id/bvi",//搜素用户-用户-小红书号

    videoNote_userIcon: "com.xingin.xhs:id/matrixAvatarView",//视频笔记用户头像
    videoNote_userNickName: "com.xingin.xhs:id/matrixNickNameView",//昵称
    videoNote_back: "com.xingin.xhs:id/backButton",//视频笔记返回上一页

    picwordNote_userIcon: "com.xingin.xhs:id/avatarLayout",//图文笔记用户头像节点
    picwordNote_nickName: "com.xingin.xhs:id/nickNameTV",//图文笔记昵称
    picwrodNote_back: "com.xingin.xhs:id/m0",//图文笔记返回

    userPage_userView: "com.xingin.xhs:id/c0c",//用户信息外框
    userPage_copyLink: "com.xingin.xhs:id/b6i",//复制用户链接
    userPage_sharePage: "com.xingin.xhs:id/d3m",//分享至页面
    userPage_shareBut: "com.xingin.xhs:id/cki",//用户主页右上角分享按钮
    userPage_nickName: "com.xingin.xhs:id/cl7",//用户主页昵称
    userPage_xhsId: "com.xingin.xhs:id/cl8",//用户主页小红书id
    userPage_concern: "com.xingin.xhs:id/kj",//关注
    userPage_fans: "com.xingin.xhs:id/akz",//粉丝
    userPage_praiseAndCollection: "com.xingin.xhs:id/bdd",//点赞和收藏
    userPage_back: "com.xingin.xhs:id/ckh",//用户主页返回
    userPage_messageIcon: "com.xingin.xhs:id/dxo",//用户主页私信图标
    userPage_gender: "com.xingin.xhs:id/cl_",//性别
    userPage_warning: "com.xingin.xhs:id/byn",//被封用户警告标志
    userPage_warningText: "com.xingin.xhs:id/bz_",//被封“用户违反社区规则”
    privateMessage_input: "com.xingin.xhs:id/zn",//私信输入框
    privateMessage_sendBut: "com.xingin.xhs:id/zs",//私信发送按钮
    privateMessage_successResult: "com.xingin.xhs:id/d2w",//私信成功提示，由于对方没有关注你,....

    homePage_bottom_text: "com.xingin.xhs:id/db6",//首页，商城，消息，我这四个标签同一个id
    homePage_fabuIcon: "com.xingin.xhs:id/b3k",//发布笔记图标id
}
const xhs_permissions_point = {//小红书权限坐标
    x: 510,
    y: 1120
}
const xhs_storage_point = {
    x: 501,
    y: 647
}
const xhs_location_point = {
    x: 510,
    y: 492
}
const xhs_adressbook_point = {
    x: 473,
    y: 1314
}
//ui参数对象
let collectInfo = {
    airMode: null,//多少个账号后打开飞行模式
    taskType: "",//任务类型
    noteType: "",//笔记类型
    content: "",//私信内容
    collectNumber: "",//采集人数
    messageNumber: "",//私信所少人数切换账号
    startTime: "",//开始采集时间
    endTime: "",//结束时间
    splideTimes: "",//下滑次数
    keywords: "",
    collect_startTime: "",//采集开始时间
    collect_endTime: "",//采集结束时间
    isTimerTask: false,
    flush: false,
    flushNum: 0,
    one: false,
    two: false,
    jumpLinks: "",
}
let userInfo = {
    nickName: "",//昵称
    xhsId: "",//小红书id
    gender: "",//性别
    constellation: "",//星座
    address: "",//地理位置
    introduction: "",//简介
    label: "",//标签,如美妆博主
    concern: "",//关注
    fans: "",//粉丝
    praiseAndCollection: ""//获赞和收藏
};
let userInfoList = [];//保存采集后的用户信息，这是个数组
let noteList = [];//保存采集的笔记数量
let userMap = new Map();
let nickname_map = new Map();
let userInfoCount = 0;//统计用户总数


/**
 *  随机睡眠
 * @param start  秒
 * @param end 秒
 */
function randomSleep(start, end) {
    sleep(random(start, end) * 1000);
}


/**
 * 初始化关键字信息
 */
function initKeyWords() {
    let keywords = file.readLine(keyword_path, 1);
    collectInfo.keywords = keywords;
    logd("关键字:" + keywords);
    if (keywords == null) {
        logd("关键字为空,默认为keyword=穿搭");
        collectInfo.keywords = "穿搭";
    }
    // file.deleteLine(keyword_path, 1, null);
    logd("关键字初始化完成！！！");
}

/**
 * 初始化ui参数
 */
function initUiparaments() {
    let airMode = ui.getShareData("airMode");
    // logd("airMode=" + airMode);
    let taskType = ui.getShareData("taskType")
    logd("任务类型=" + taskType);
    let noteType = ui.getShareData("noteType");
    logd("笔记类型=" + noteType);
    let content = ui.getShareData("content");
    // logd("content=" + content);
    let collectNumber = ui.getShareData("collectNumber");
    // logd("collectNumber=" + collectNumber);
    let messageNumber = ui.getShareData("messageNumber");
    // logd("messageNumber=" + messageNumber);
    let startTime = ui.getShareData("startTime")
    // logd("startTime=" + startTime);
    let endTime = ui.getShareData("endTime")
    // logd("endTime=" + endTime);
    let splideTimes = ui.getShareData("splideTimes");
    // logd("splideTimes=" + splideTimes);
    let collect_startTime = ui.getShareData("collect_startTime")
    // logd("startTime=" + startTime);
    let collect_endTime = ui.getShareData("collect_endTime")

    let two = ui.getConfig("messageTwo");
    let one = ui.getConfig("one");

    collectInfo.airMode = airMode || 4;
    collectInfo.taskType = taskType;
    collectInfo.noteType = noteType;
    collectInfo.content = content || 0;
    collectInfo.collectNumber = collectNumber || 10;
    collectInfo.messageNumber = messageNumber || 5;
    collectInfo.startTime = startTime || 1;
    collectInfo.endTime = endTime || 3;
    collectInfo.splideTimes = splideTimes || 5;
    collectInfo.collect_startTime = collect_startTime || 1;
    collectInfo.collect_endTime = collect_endTime || 3;
    collectInfo.flush = ui.getShareData("flush");
    collectInfo.flushNum = ui.getShareData("flushNum");
    collectInfo.one = one;
    collectInfo.two = two;
    if (!file.exists(config_Path)) {
        file.create(config_Path);
    }
    file.writeFile(taskType, config_Path);
    logw("flush=" + collectInfo.flush);
    logw("flushNum=" + collectInfo.flushNum);
    logd("参数初始化完成");


}


/**
 * xxmj备注无效账号
 */
function xxmjRemark() {
    click(id(enumId.xxmj_remarkId));
    sleep(1000);
    let input = id(enumId.xxmj_rename_InputId).getOneNodeInfo(1000);
    sleep(1000);
    let name = "无效账号" + time();
    input.inputText(name);
    sleep(1000);
    click(id(enumId.xxmj_rename_save));
    sleep(1000);
}

// switch_to_flight_mode();

main();

function choseTask() {
    if (collectInfo.taskType == "综合采集" || collectInfo.taskType == "最热采集" || collectInfo.taskType == "最新采集") {
        initKeyWords();//初始化关键字，读取一行删除一行
        sleep(2000);
        logd(collectInfo.keywords + "---" + collectInfo.taskType + "---" + collectInfo.noteType);
        logd(collectInfo.collectNumber + "----" + collectInfo.splideTimes);
        collect_keywords_userinfo(collectInfo.keywords, collectInfo.taskType, collectInfo.noteType, collectInfo.collectNumber, collectInfo.splideTimes);
        logd("采集结束....");
        sleep(2000);
        URL_intent(home_url);
        sleep(2000);
        home();
    } else if (collectInfo.taskType == "首页采集") {
        randomSleep(collectInfo.collect_startTime, collectInfo.collect_endTime);
        collectionHomePage(collectInfo.collectNumber);
        home();
    } else if (collectInfo.taskType == "跳转采集") {
        sleep(2000);
        // openXHS();
        let noteUrl = initNoteUrl(this.jumpLink_path);
        sleep(2000);
        let rs = URL_intent(noteUrl);
        sleep(2000);
        if (rs) {
            logd("跳转成功");
        } else {
            logd("跳转失败,链接为空");
            exit();
        }
        collectCommentsUserinfo(collectInfo.collectNumber, noteUrl);
        home();
    } else if (collectInfo.taskType == "跳转私信") {
        logd("开始跳转私信....");
        let airModeNumber = collectInfo.airMode;
        let sum = 0;
        let switch_user_sum = 0;//切换飞行模式的用户计数
        while (true) {
            protectXhsRunning();
            let time = random(collectInfo.startTime, collectInfo.endTime);
            sleep(time * 1000);
            let sendRs = sendMessage(this.xhs_message_jumpLink, collectInfo.content);
            if (sendRs == -1) {//当账号被禁言或者账号被其他人登录时返回-1,切换下一个账号
                airSwitchSize = 2;
            }
            if (sendRs == 0) {
                switch_to_flight_mode();
            }
            //回到首页
            URL_intent(home_url);
            sum++;
            logd("sum====>" + sum);
            logd(switch_user_sum);
            logd(!(sum % switch_user_sum));
            let temp = collectInfo.messageNumber;
            logd("temp=" + temp);
            logd("sum%temp=" + sum % temp);
            logd("airSwitchSize=" + airSwitchSize);
            logd("私信成功总数：" + sentMessageSuccess_count);
            if ((sum % temp) == 0 || airSwitchSize == 2) {
                airSwitchSize = 0;
                logd("开始切换账号");
                let r = false;
                while (true) {
                    r = switch_user_environment();
                    if (r) {
                        switch_user_sum++;
                        break;
                    }
                }
                if (r) {
                    logd("切换用户计数:" + switch_user_sum);
                    logd("airModeNumber:" + airModeNumber);
                    if ((switch_user_sum % airModeNumber) === 0) {
                        logd("开始切换飞行模式");
                        shell.stopApp("com.xingin.xhs");
                        switch_to_flight_mode();//切换飞行模式
                        sleep(500);
                        let arr = openXHS();
                        // cancelInterval(arr[0]);
                    }
                }

            }
        }
    } else if (collectInfo.taskType == "搜ID私信") {
        logd("开始搜索ID私信....");
        let airModeNumber = collectInfo.airMode;
        let sum = 0;
        let switch_user_sum = 0;//切换飞行模式的用户计数
        let chat_Path = this.chat_Path + collectInfo.content + ".txt";
        let chatContent = initChat(chat_Path);
        while (true) {
            randomSleep(1, 3);
            let xhsId = initMessageUser(userId_path);
            let rs = searchByXhsId(xhsId);
            if (rs == 0) {
                file.deleteLine(userId_path, 1, null);
                continue;
            }
            sleep(1000);
            let sendRs = startSendMessage(chatContent, userId_path);
            if (sendRs == -1) {
                airSwitchSize = 2;
            }
            if (sendRs == 0) {
                switch_to_flight_mode();
            }
            sleep(2000);
            sum++;
            logd("sum====>" + sum);
            logd(switch_user_sum);
            logd(!(sum % switch_user_sum));
            let temp = collectInfo.messageNumber;
            logd("temp=" + temp);
            logd("sum%temp=" + sum % temp);
            logd("airSwitchSize=" + airSwitchSize);
            logd("私信成功总数：" + sentMessageSuccess_count);
            if ((sum % temp) == 0 || airSwitchSize == 2) {
                airSwitchSize = 0;
                logd("开始切换账号");
                let r = false;
                while (true) {
                    r = switch_user_environment();
                    if (r) {
                        switch_user_sum++;
                        break;
                    }
                }
                if (r) {
                    logd("切换用户计数:" + switch_user_sum);
                    logd("airModeNumber:" + airModeNumber);
                    if ((switch_user_sum % airModeNumber) === 0) {
                        logd("开始切换飞行模式");
                        shell.stopApp("com.xingin.xhs");
                        switch_to_flight_mode();//切换飞行模式
                        sleep(3000);
                        openXHS();
                        // cancelInterval(arr[0]);
                    }
                    sleep(2000);
                }
            }
        }

    } else if (collectInfo.taskType == "用户主页采集") {
        logd(1);
        while (true) {
            // openXHS();
            sleep(2000);
            let url = initMessageUrl(xhs_user_home);
            logd("url====" + url);
            if (url.length == 0) {
                logd("采集结束....");
                break;
            }
            let schema = "xhsdiscover://user/" + url;
            logd("跳转到用户主页...");
            URL_intent(schema);
            sleep(2000);
            getUserInfo(null);
        }
    }
}

/**
 * 刷新首页
 */
function flushFirstPageData() {
    let firstPage = text("首页").index(0).getOneNodeInfo(1000);
    let x = random(firstPage.bounds.left, firstPage.bounds.right);
    let y = random(firstPage.bounds.top, firstPage.bounds.bottom);
    doubleClickPoint(x, y);
}

/**
 * 防止私信时进入笔记
 * @returns {boolean}
 */
function protectXhsRunning() {
    if (!xhsIsLoginHome()) {
        if (getRunningPkg() == xhsPkg) {
            if (getRunningActivity()=="com.xingin.login.activity.WelcomeActivity") {
                return true;
            }
            if (getRunningActivity()=="com.xingin.login.activity.LoginActivity") {
                return true;
            }
            back();
        } else {
            utils.openApp(xhsPkg);
            sleep(500);
            if (!xhsIsLoginHome()) {
                back();
            }
        }
    }
}

function main() {

    // logd("保持设备唤醒："+ device.keepScreenOn());
    setExceptionCallback(function (msg) {
        logd(" 异常停止消息: " + msg);
        pageCount = file.readLine(page_count, 1);
        let taskType = file.readFile(config_Path);
        collectInfo.taskType = taskType;
        restartScript(null, true, 3);
    });

    //开始再这里编写代码了！！
    //如果自动化服务正常
    // initLogWindow();
    if (!autoServiceStart(3)) {
        logd("自动化服务启动失败，无法执行脚本")
        exit();
        return;
    }
    let result = daemonEnv(true);
    logd("守护激活:" + result);
    setLogFixedViewEx();
    if (!file.exists(logPath)) {
        file.create(logPath)
    }
    let logName = time() + ".txt";
    let s = setSaveLogEx(true, logPath, 1024 * 1024, logName);
    logd("日志路径:" + s);
    initUiparaments();
    if (collectInfo.one == true) {
        logw("开启定时重启任务...");
        let timer = ui.getConfig("restartOne") * 60 * 1000;
        logw("重启脚本时间间隔：" + timer);
        setInterval(function () {
            pageCount = file.readLine(page_count, 1);
            restartScript(null, true, 3)
        }, timer);
    }
    logd("是否定时重启私信脚本:" + collectInfo.two);
    if (collectInfo.two == true) {
        logw("开启定时重启私信...");
        let messageTime = ui.getConfig("restartTwo") * 60 * 1000;
        logw("重启脚本时间间隔：" + messageTime);
        setInterval(function () {
            restartScript(null, true, 3)
        }, messageTime);
    }
    openXHS();
    // asynchCheckLoginStatus();
    // autoBackHome();
    logd("开始进入任务选择....");
    protectXhsRunning();
    choseTask.call(this);
}


/**
 * 根据小红书id查找用户
 * @param xhsId
 * @param xhsName
 */
function searchByXhsId(xhsId) {
    backHome();
    randomSleep(1, 3);
    logd("进入用户ID搜索 .....");
    randomSleep(1, 3);
    if (!xhsIsLoginHome()) {
        utils.openApp(xhsAppName);
        sleep(500);
    }
    let searchIcon = id(enumId.searchClickIcon);
    let result = click(searchIcon);
    randomSleep(1, 3);
    if (result) {
        //进入搜索狂
        logd("进入搜索栏......");
        let searchInput = id(enumId.searchInput);
        let rs = waitExistNode(searchInput, 2000);
        if (rs) {
            logd("输入ID:" + xhsId);
            let node = searchInput.getOneNodeInfo(2000);
            let rs1 = node.inputText(xhsId);
            sleep(2000);
            logd("点击搜索");
            let search = id(enumId.searchClickBut);
            let rs2 = click(search);
            logd(rs2 ? "搜索成功" : "搜索失败");
            sleep(1000);
            clickText("用户");
            sleep(2000);
            let noteArray = id(enumId.searchResult_NoteParent).getOneNodeInfo(1000);
            if (noteArray == null) {
                logd("用户搜索为空，返回上一步");
                return false;
            }
            let tempText = "小红书号：" + xhsId;
            let textNode = textMatch(tempText + ".*").getOneNodeInfo(2000);
            if (textNode) {
                textNode.click();
                sleep(1000);
                if (checkMessageUserWarning()) {
                    logd("该用户已被封禁，无法私信");
                    return 0;
                }
            }
            return true;
        }
    } else {
        return false;
    }
    return true;
}


/**
 * 回到小红书首页
 */
function backHome() {
    while (true) {
        if (xhsIsLoginHome()) {
            break;
        }
        backs(1, 3);
    }
}

function checkXXmjIsopen() {
    return has(id(enumId.xxmj_currentIcon)) || has(id(enumId.xxmj_createNew));

}

/**
 * 初始化私信用户
 * @param url
 * @returns {string}
 */
function initMessageUser(url) {
    logd("xhs_message_userId.txt配置文件是否存在" + file.exists(url));
    let user = file.readLine(url, 1);
    if (user) {
        user = user.toString();
    } else {
        toast("私信用户ID已发送完");
        exit();
    }
    logd(user);
    // file.deleteLine(url, 1);
    return user;
}

/**
 * 初始化笔记路径
 */
function initNoteUrl(note_jumpLink_path) {
    let url = file.readLine(note_jumpLink_path, 1);
    if (url) {
        url = url.toString();
        url = url.match("profile/[0-9][a-zA-Z0-9]{0,24}");
        // logd(url);
        // url = url.toString().substr(0, 24);
        url = url[0].split("/")[1];
        logd("url=" + url);
        return "xhsdiscover://item/" + url;
    }
    return null;
}

/**
 * 打开小红书
 */
function openXHS() {
    let result = launch(xhsPkg, 3000, 3);
    if (result) {
        logd("打开小红书......");
        URL_intent(home_url);
        let loginThis = id(enumId.lognThisAccount);
        let phoneLogin = id(enumId.phoneLogin);
        let phoneText = textMatch(".*登录后更精彩.*");

        if (has(loginThis) || has(phoneLogin) || has(phoneText)) {
            isUsefulAccount = 0;
            switch_user_environment();
        }
    }
    let t1 = setInterval(function () {
        let node6 = id(enumId.xhs_tackingPictures);
        if (has(node6)) {
            click(node6);
            sleep(500);
        }
        let node0 = id(enumId.xhsWarnTips);
        if (has(node0)) {
            click(id(enumId.xhsWarnTips_agreeBut));
            sleep(500);
        }
        let node = id(enumId.choseHobby_title);
        if (has(node)) {
            click(id(enumId.choseHobby_jump));
            sleep(500);
        }
        let node1 = id(enumId.newVersion);
        if (has(node1)) {
            click(id(enumId.newVersionExit));
            sleep(500);
        }
        let node2 = id(enumId.xhsAccessSpace);
        if (has(node2)) {
            click(id(enumId.xhsAccessSpace_allowBut));
            sleep(500);
        }
        let node3 = id(enumId.xhsAccessMedia);
        if (has(node3)) {
            click(id(enumId.xhsAccessMedia_allowBut));
            sleep(500);
        }

    }, 2000)

    return true;
}

function asynchCheckLoginStatus() {
    logd("开启异步线程检查登录状态....");
    let tid = thread.execAsync(function () {
        while (true) {
            let loginThis = id(enumId.lognThisAccount);
            if (has(loginThis)) {
                logd("账号被登陆");
                isUsefulAccount = 0;
                let rs = switch_user_environment();
            }
            let phoneLogin = id(enumId.phoneLogin);
            if (has(phoneLogin)) {
                logd("账号被登陆");
                isUsefulAccount = 0;
                switch_user_environment();
            }
            let phoneText = textMatch(".*登录后更精彩.*");
            if (has(phoneText)) {
                logd("账号被登陆");
                isUsefulAccount = 0;
                switch_user_environment();
            }

            if (thread.isCancelled(tid)) {
                break;
            }
        }
    });

}


function autoBackHome() {
    let t = setInterval(function () {
        if (getRunningPkg() != xhsPkg) {
            logd("小红书app不在应用最上层");
            utils.openApp(xhsPkg);
            if (!xhsIsLoginHome()) {
                for (let i = 0; i < 3; i++) {
                    back();
                    if (xhsIsLoginHome()) {
                        break;
                    }
                }
            }
        }
    }, 5000);
}

/**
 * 根据关键字采集笔记用户信息
 */
function collect_keywords_userinfo(keywords, searchType, noteType, collectionNumber, splideTimes) {
    sleep(1000);
    //     //默认滑动更新三次数据
    logd("1");
    sleep(1000);
    search(keywords, searchType, noteType);
    sleep(1000);
    splide(search_page_viewId, splideTimes, true);
    do {
        sleep(1000);
        console.time("1");
        startCollectNode();//关键字采集
        splide(search_page_viewId, 1, true);
        logd("采集一个任务时间：" + console.timeEnd("1") / 4000 + "秒");
        logd("结束时长度：" + this.userInfoCount);
        userMap.clear();
        sleep(3 * 1000);
        if (this.userInfoCount > collectionNumber) {
            logd("采集人数已达成");
            break;
        }
    } while (true);
    logd("采集结束....");
}

/**
 * 图文笔记返回上一页
 */
function picwordNote_back() {
    logd("返回上一页");
    let r1 = id(enumId.picwrodNote_back).getOneNodeInfo(1000);
    sleep(1000);
    if (r1) {
        r1.click();
    }
}

/**
 * 视频笔记返回上一页
 */
function videoNote_back() {
    logd("返回上一页");
    let r2 = id(enumId.videoNote_back).getOneNodeInfo(1000);
    sleep(1000);
    if (r2) {
        r2.click();
    }
}

/**
 * 首页采集
 */
function homePageCollect() {
    logd("开始采集笔记...");
    //用户主页的节点id
    let notes = id(enumId.homePage_noteView).getNodeInfo(3000);
    sleep(3000);
    if (notes === null) {
        // backs(1,3);
        return false;
    }
    for (let i = 0; i < notes.length; i++) {
        let n = notes[i];
        // logd(JSON.stringify(n));
        if (n.id != enumId.homePage_noteView) {
            continue;
        }
        clickCenter(n.bounds);
        sleep(1000);
        logd("是否视频笔记:" + checkVideoNote());
        sleep(2000);
        // cancelInterval(t1);
        if (checkVideoNote()) {
            logd(1);
            let node = id(enumId.videoNote_userNickName).getOneNodeInfo(1000);
            let wifiText = textMatch(".*当前处于非 WiFi 环境.*");
            if (has(wifiText)) {
                clickText("知道了");
            }
            if (node) {
                node.click();
                sleep(2 * 1000);
                // cancelInterval(t1);
                let ret = getUserInfo(enumId.videoNote_back);
                videoNote_back();
                logd(3);
                continue;
            }
        } else {
            logd(2);
            let userIcon = id(enumId.picwordNote_nickName);
            if (userIcon == null) {
                backs(1, 3);
                break;
            }
            sleep(2000);
            clickRandom(userIcon);
            let ret = getUserInfo(enumId.picwrodNote_back);
            picwordNote_back();
            continue;
        }
        sleep(1000);
    }

}

/**
 * 是否视频笔记
 * @returns {bool|布尔型}
 */
function checkVideoNote() {
    return has(id(enumId.videoNote_userIcon));
}

/**
 * 返回关键字搜索页面
 */
function backSearchResult() {

    while (true) {
        let searchList = id(enumId.searchResult_noteView);
        if (has(searchList)) {
            break;
        }
        backs(1, 3);
    }
}


/**
 * 采集符合要求的笔记
 * @param collectType 采集类型，参数位（首页采集，关键字搜索）
 */
function startCollectNode() {
    logd("采集关键字搜索笔记...");

    let searchList = id(enumId.searchResult_noteView).getNodeInfo(1000);
    //用户主页的节点id
    if (searchList == null) {
        backSearchResult();
        return;
    }
    for (let i = 0; i < searchList.length; i++) {
        let n = searchList[i];
        if (n.clz != "android.widget.ImageView") {
            continue
        }
        // logd(JSON.stringify(n.bounds));
        let x = 0.5 * (n.bounds.left + n.bounds.right);
        let y = 0.5 * (n.bounds.top + n.bounds.bottom);
        clickPoint(random(x, x + 50), random(y, y + 50));
        sleep(1000);
        let isVideoNote = checkVideoNote();
        logd("是否视频:" + isVideoNote);
        if (isVideoNote) {
            let node = id(enumId.videoNote_userNickName).getOneNodeInfo(1000);
            let wifiText = textMatch(".*当前处于非 WiFi 环境.*");
            if (has(wifiText)) {
                clickText("知道了");
                sleep(500);
            }
            if (node) {
                sleep(1000);
                node.click();
                sleep(1 * 1000);

                let ret = getUserInfo(enumId.videoNote_back);
                if (!ret) {
                    videoNote_back();
                }
                sleep(1000);
            }
        } else {
            let node = id(enumId.picwordNote_nickName);
            if (node) {
                sleep(1000);
                clickRandom(node);
                sleep(1 * 1000);
                let ret = getUserInfo(enumId.picwrodNote_back);
                if (!ret) {
                    picwordNote_back();
                }
                sleep(1000);
            }
        }

    }

}


/**
 * 获取小红书博主的用户信息
 * @param selector
 */
function getUserInfo(noteBackId) {
    sleep(1 * 1000);//等待加载视频
    logd("进入用户主页面...开始采集数据...");
    // protectUserPage()
    if (!checkUserPage()) {
        backs(1, 2000);
    }

    let nickName = getNodeAttrs(id(enumId.userPage_nickName), "text");
    sleep(2 * 1000);
    if (nickName == null) {
        logd("昵称为空，跳过");
        click(id(enumId.userPage_back));//返回上一页
        return false;
    }
    userInfo.nickName = nickName.toString();
    if (userMap.has(userInfo.nickName)) {
        logd("用户已存在，跳过");
        click(id(enumId.userPage_back));//返回上一页
        sleep(2000);
        clickRandom(id(noteBackId));
        sleep(1000);
        return false;
    } else {
        userMap.set(userInfo.nickName, userInfo.nickName);
    }
    //获取用户页码跳转专用链接
    let shareIcon = id(enumId.userPage_shareBut).getOneNodeInfo(1000);
    sleep(1000);
    if (shareIcon == null) {
        clickRandom(id(noteBackId));//继续返回
        return false;
    }
    shareIcon.click();
    sleep(1000);
    let sharePage = id(enumId.userPage_sharePage);
    if (sharePage == null) {
        return;
    }
    sleep(1000);
    //点击复制链接
    let clip_result = null;
    clickText("复制链接");
    sleep(1000);
    clip_result = utils.getClipboardText();//读取剪贴板结果
    let url = clip_result.split("?xhsshare=");

    let xhs_id = getNodeAttrs(id(enumId.userPage_xhsId), "text");
    // sleep(1 * 1000);
    if (xhs_id == null) {
        return false;
    }
    xhs_id = xhs_id.toString();
    xhs_id = xhs_id.split("：")[1];
    logd("小红书号:" + xhs_id);
    userInfo.xhsId = xhs_id;
    userInfo.concern = getNodeAttrs(id(enumId.userPage_concern), "text");//关注数
    userInfo.fans = getNodeAttrs(id(enumId.userPage_fans), "text");//粉丝数
    userInfo.praiseAndCollection = getNodeAttrs(id(enumId.userPage_praiseAndCollection), "text");//点赞数和收藏数
    logd("用户信息:" + JSON.stringify(userInfo));
    logd("开始写入字典....");
    // this.userMap.set(nickName, userInfo);
    logd("当前用户信息字典长度:" + userInfoCount);
    if (userInfo.nickName != null) {
        let info = userInfo.nickName + "---" + userInfo.xhsId + "---" + userInfo.concern + "---" + userInfo.fans + "---" + userInfo.praiseAndCollection + "---" + url[0];
        let t = file.appendLine(info, userinfo_Path);
        userInfoCount++;
        logd("追加写入文件" + t);
    }
    logd("用户信息采集完成，返回上一页");
    click(id(enumId.userPage_back));//返回上一页
    sleep(1000);
    if (noteBackId != null) {
        clickRandom(id(noteBackId));//继续返回
        return true;
    }
    return true;
}


/**
 * 根据关键字搜索
 * @param keywords
 * @param taskType 查询类型 ,默认 全部
 * @param noteType 笔记类型，默认，全部
 * @returns {boolean}
 */
function search(keywords, searchType, noteType) {
    logd("进入关键字搜索 .....");
    sleep(3000);
    searchType = searchType || "综合";
    noteType = noteType || "全部";
    // logd("==========" + noteType);
    let searchSelector = id(enumId.searchClickIcon);
    let result = click(searchSelector);
    sleep(2000);
    if (result) {
        //进入搜索狂
        logd("进入搜索栏......");
        let searchInput = id(enumId.searchInput);
        let rs = waitExistNode(searchInput, 2000);
        if (rs) {
            logd("输入关键字:" + keywords);
            let node = searchInput.getOneNodeInfo(2000);
            node.inputText(keywords);
            sleep(2000);
            logd("点击搜索");
            let search = id(enumId.searchClickBut);
            let rs2 = click(search);
            logd(rs2 ? "搜索成功" : "搜索失败");
            sleep(2000);
            logd("采集类型:" + searchType);
            if (searchType == "最新采集") {
                logd(1);
                let x = rSwipe.getNodeCenterX(id(enumId.searchResult_new));
                let y = rSwipe.getNodeCenterY(id(enumId.searchResult_new));
                clickPoint(x, y);
            } else if (searchType == "最热采集") {
                logd(2);
                let x = rSwipe.getNodeCenterX(id(enumId.searchResult_hot));
                let y = rSwipe.getNodeCenterY(id(enumId.searchResult_hot));
                clickPoint(x, y);
            } else {
                clickText("综合");
            }
            sleep(1000);
            if (noteType == "视频") {
                logd("选择视频");
                let x = rSwipe.getNodeCenterX(id(enumId.searchResult_video));
                let y = rSwipe.getNodeCenterY(id(enumId.searchResult_video));
                clickPoint(x, y);
            } else if (noteType == "视频") {
                logd("选择图文");
                let x = rSwipe.getNodeCenterX(id(enumId.searchResult_pic));
                let y = rSwipe.getNodeCenterY(id(enumId.searchResult_pic));
                clickPoint(x, y);
            }
            return true;
        }
    } else {
        return false;
    }
    return true;
}

//遍历数组
function printMap(map) {
    map.forEach(function (key, value) {
        logd("key:" + key + ",value:" + JSON.stringify(value));
    })
}


/**
 * 根据ui的滑动次数向下滑动
 * @param viewId
 * @param times
 * @param direct
 * @returns {boolean}
 */``

function splide(viewId, times, direct, isPageSum) {
    if (times < 1) {
        logd("滑动次数不可为0");
        return false;
    }
    if (direct == null) {
        logd("滑动方向不可为空");
        return false;
    }
    isPageSum = isPageSum || collectInfo.isTimerTask;
    logd(isPageSum);
    if (isPageSum == true) {
        logd("定时任务,重启后先回到上一次页数");
        times = parseInt(file.readLine(page_count, 1));
    }
    // logd(3);
    sleep(2000);
    let mainPageId = id(viewId);
    if (mainPageId == null) {
        logd("当前节点不可滑动");
        return false;
    }
    let startX = 523;
    let endX = startX;
    let centerY = 970;
    let height = 1670;
    if (direct) {
        //向上滑动，x坐标不变，y坐标start小于end 1000以上
        startY = height - 200;
        endY = 0;
    } else {
        //向下滑动
        startY = centerY - (height / 4);
        endY = height;
    }
    for (let i = 0; i < times; i++) {
        sleep(2000);
        rSwipe.rndSwipe(startX, startY, endX, endY, 50, 80, 1000);
    }
    pageCount += times;
    file.writeFile(pageCount, page_count);
    logd("滑动结束....");
    return true;

}


/**
 * app内跳转页面
 */
function URL_intent(url) {
    sleep(2000);
    let rt = utils.openActivity({
        "uri": url,
    });
    return rt;
}

function autoServiceStart(time) {
    for (let i = 0; i < time; i++) {
        if (isServiceOk()) {
            return true;
        }
        let started = startEnv();
        logd("第" + (i + 1) + "次启动服务结果: " + started);
        if (isServiceOk()) {
            return true;
        }
    }
    return isServiceOk();
}


/**
 * 采集首页笔记用户信息
 * @param collectPersons
 */
function collectionHomePage(collectPersons) {
    logw("开始首页采集...");
    let r = URL_intent(home_url);
    if (r) {
        logd("跳转首页成功");
    } else {
        logd("跳转首页失败");
    }
    //根据下滑动次数后采集
    randomSleep(collectInfo.collect_startTime, collectInfo.collect_endTime);
    let times = parseInt(collectInfo.splideTimes);
    logd("times=" + times);
    splide(enumId.homePage_noteParent, times, true);
    randomSleep(collectInfo.collect_startTime, collectInfo.collect_endTime);
    //开始采集
    let splideFlushCount = 1;
    do {
        logd("进入循环....")
        if (getRunningPkg() != xhsPkg) {
            utils.openApp(xhsPkg);
        }
        if (!checkDiscoverAndHomePage()) {
            logd("当前页面不在首页发现页...");
            backs(1, 2000);
        }
        console.time("2");
        sleep(2000);
        homePageCollect();
        sleep(1000);
        splide(enumId.homePage_noteParent, 1, true);
        logd("第" + splideFlushCount + "次下滑");
        splideFlushCount++;
        logd("任务用时:" + console.timeEnd("2") / 1000 + "秒");
        logd("结束时长度：" + this.userMap.size);
        sleep(1 * 1000);
        if (collectInfo.flush) {
            if (splideFlushCount % collectInfo.flushNum == 0) {
                logd("开启首页刷新");
                flushFirstPageData();
            }
        }
        if (this.userMap.size > collectPersons) {
            logd("采集人数已达成");
            break;
        }
    } while (true);
    // writeUserInfoFile(this.userMap,this.userPath);
    logd("采集结束....");
    // printMap(this.nickname_map);0
    printMap(this.userMap);

}


/**
 * 根据链接跳转到笔记采集评论区用户信息
 * @param collectPersons
 */
function collectCommentsUserinfo(collectPersons, url) {
    logd("开始跳转到笔记...");
    //图文链接和视频链接的评论区内容都一样
    //模拟向上滑动
    let i = 0;
    while (true) {
        let exist = waitExistNode(id("com.xingin.xhs:id/noteContentLayout"), 2000);
        logd("exist===>" + exist);
        sleep(1000);
        if (!exist) {
            URL_intent(url);
            sleep(3000);
            continue;
        }
        sleep(1000);
        rSwipe.rndSwipe(500, 1500, 500, 300, 50, 80, 1000);
        sleep(1000);
        let node = id("com.xingin.xhs:id/dvy");
        if (has(node)) {
            break;
        }
    }
    sleep(2000);
    logd("开始滚动...");
    let node = id("com.xingin.xhs:id/c_z").scrollable(true).getOneNodeInfo(10000);
    let nick_name_map = new Map();
    while (true) {
        sleep(1000);
        rSwipe.rndSwipe(500, 1500, 500, 300, 50, 80, 1000);
        // splide("com.xingin.xhs:id/c_z",1,true);
        sleep(1000);
        let user = id("com.xingin.xhs:id/dvy").getOneNodeInfo(2000);
        sleep(1000);
        logd("user:" + user);
        let nickName = getNodeAttrs(id("com.xingin.xhs:id/dvy"), "text");
        sleep(1000);
        logd("nickName:" + nickName);
        if (nickName == null) {
            sleep(2000);
            let rs = isScrollEnd("UP", node);
            if (rs) {
                logd("评论区已到底部，采集完毕！！！");
                break;
            }
            sleep(1000);
            let selector = clz("android.widget.FrameLayout").getOneNodeInfo(1000);
            if (selector) {
                selector.refresh();
            } else {
                logd("无节点");
            }
            logd("昵称多次位null时,节点刷新====>" + r);
            continue;
        }
        sleep(1000);
        if (user == null) {
            continue;
        }
        let r = user.click();
        sleep(1000);
        if (!r) {
            continue;
        }
        let user_result = getUserInfo(null);
        if (!user_result) {//当昵称为空时，跳入下一个循环
            continue;
        }
        if (userMap.size > collectPersons) {
            logd("完成采集数量:" + userMap.size);
            break;
        }

    }
    sleep(2000);
}

/**
 * 是否在用户主页
 * @returns {bool|布尔型}
 */
function checkUserPage() {
    let nickName = id(enumId.userPage_nickName);
    sleep(2000);
    if (!has(nickName)) {
        return false;
    }
    let userView = id(enumId.userPage_userView);
    sleep(2000);
    if (!has(userView)) {
        return false;
    }
    return true;
}

/**
 * 检查用户是否违反社区规则
 */
function checkMessageUserWarning() {
    let warnIcon = id(enumId.userPage_warning);
    let warnText = textMatch(".*因相关投诉该账户违反.*");
    return has(warnIcon) || has(warnText);
}

/**
 * 发送私信动作
 * @param content
 * @param xhs_id_Path
 * @returns {number}
 */
function startSendMessage(content, xhs_id_Path) {
    if (checkLostLogin()) {
        logd("当前账号已被登录，切换下一个");
        isUsefulAccount = 0;
        return -1;
    }
    let chatBut = id(enumId.userPage_messageIcon).getOneNodeInfo(2000);
    if (chatBut) {
        chatBut.click();
        sleep(500);
        let chatInput = id(enumId.privateMessage_input).getOneNodeInfo(2000);
        if (chatInput) {
            chatInput.inputText(content);
            while (true) {
                let sendBut = id(enumId.privateMessage_sendBut).getOneNodeInfo(500);
                sendBut.click();
                sleep(500);
                if (has(id(enumId.privateMessage_successResult))) {
                    break;
                } else {
                    sleep(3000);
                    break;
                }
            }
            sleep(500);
            let banned = textMatch(".*禁言.*").getOneNodeInfo(1000);
            if (banned != null) {
                logd("当前账号被禁言，马上切换下一个");
                return -1;
            }
            let banned2 = textMatch(".*封号.*").getOneNodeInfo(1000);
            if (banned2 != null) {
                logd("当前账号被封，马上切换下一个");
                return -1;
            }
            let banned3 = textMatch(".*今天的招呼次数已经用完啦～.*").getOneNodeInfo(1000);
            if (banned3 != null) {
                logd("当前账号招呼次数已用完，马上切换下一个");
                return -1;
            }
            let successResult = id(enumId.privateMessage_successResult);
            if (has(successResult)) {
                sentMessageSuccess_count++;
                oneUserSendCount = 0;
                let res = file.deleteLine(xhs_id_Path, 1, null);
                logd("私信成功后删除链接:" + res);
                return 1;
            } else {
                logd("没有返回结果发送失败");
                oneUserSendCount++;
                airSwitchSize++;
                return -1;
            }
        }
    }
}



/**
 * 根据小红书id发送私信
 * @param xhs_id
 * @param chat_str
 * @Return 0表示当前用户亦需要切换，1表示可以继续使用当前用户
 */
function sendMessage(xhs_id_Path, chat_str) {
    if (checkLostLogin()) {
        logd("当前账号已被登录，切换下一个");
        isUsefulAccount = 0;
        return -1;
    }
    let chat_Path = this.chat_Path + chat_str + ".txt";
    let content = initChat(chat_Path);
    logd(content);
    if (oneUserSendCount == 2) {
        let res = file.deleteLine(xhs_id_Path, 1, null);
        logd("该用户链接无法私信，删除链接：" + res);
    }
    let chatUrl = initMessageUrl(xhs_id_Path);
    logd(chatUrl);
    if (chatUrl == null || chatUrl.length == 0) {
        logd("私信链接为空");
        file.appendLine(sentMessageSuccess_count, sentMessCountPath);
        exit();
    }

    let schema = "xhsdiscover://user/" + chatUrl;
    URL_intent(schema);
    logd("跳转到用户个人页码");

    if (checkMessageUserWarning()) {//检查用户是否被封，如果被封直接删除当前链接
        let res = file.deleteLine(xhs_id_Path, 1, null);
        logd("该用户被封，删除:" + res);
        return 1;
    }
    sleep(500);
    if (checkLostLogin()) {
        logd("当前账号已被登录，切换下一个");
        isUsefulAccount = 0;
        return -1;
    }

    return startSendMessage(content, xhs_id_Path);
}

/**
 * 检查登录是否掉了
 */
function checkLostLogin() {
    let res = textMatch(".*登录后更精彩.*").getOneNodeInfo(1000);
    return res != null ? true : false;
}




/**
 * 私信链接初始化
 * @param path
 * @returns {string}
 */
function initMessageUrl(path) {
    logd("开始读取要私信的连接");
    let jumpLink = file.readLine(path, 1);
    if (jumpLink != null) {
        let url = jumpLink.toString();
        if (url == null || url == "") {
            logd("第一行为空,删除第一行");
            file.deleteLine(path, 1);
            return false;
        }
        url = url.match("profile/[0-9][a-zA-Z0-9]{0,24}");
        url = url[0].split("/")[1];
        logd("读取私信用户链接成功");
        return url;
    } else {
        logd("私信用户链接为空");
        toast("私信用户链接为空...");
        return "";
    }
}

/**
 * 读取私信内容
 * @param path
 * @returns {string}
 */
function initChat(path) {
    logd("开始读取要私信内容");
    let content = file.readLine(path, 1);
    if (content == null || content == "") {
        logd("私信内容为空");
    }
    return content;
}

/**
 * 切换飞行模式
 */
function switch_to_flight_mode() {
    let isConnect = laoleng.http.isConnectAble();//网络是否链接
    if (isConnect) {
        while (true) {
            sleep(1000);
            let rs = openAirMode2();//打开飞行模式
            if (rs) {
                logd("打开飞行模式成功:" + rs);
                break;
            }

        }
        let i = 1;
        while (i <= 30) {
            logd("计时第" + i + "秒");
            sleep(1000);
            i++;
        }
        while (true) {
            sleep(1000);
            let rs = openAirMode2();
            sleep(2000);
            if (rs) {
                logd("关闭飞行模式成功:" + rs);
                break;
            }
        }
        sleep(2 * 1000);
        // logd("切换后ip："+ip1);
        while (true) {
            sleep(1000);
            let isConnect = laoleng.http.isConnectAble();//网络是否链接
            if (isConnect) {
                logd("网络恢复正常");
                utils.openAppByName(xhsAppName);
                break;
            }
        }
    }
}

/**
 * 切换飞行模式
 */
function openAirMode() {
    utils.openIntentAction("android.settings.AIRPLANE_MODE_SETTINGS");//打开手机设置页面
    sleep(1000);
    splide(enumId.huaweiPhone_settingPage, 1, true);
    sleep(random(500, 1000));
    splide(enumId.huaweiPhone_settingPage, 3, false);
    sleep(random(500, 1000));
    let isConnect = false;
    while (true) {
        let node = id(enumId.huaweiPhone_airModeBut).getOneNodeInfo(1000);
        if (node) {
            node.click();
            sleep(1000);
            isConnect = laoleng.http.isConnectAble();
            sleep(1000);
            if (!isConnect) {
                break;
            }
        }
    }
    return !isConnect;
}

/**
 * 打开飞行模式
 */
function openAirMode2() {
    let isConnect = false;
    while (true) {
        let result = openNotification();
        sleep(1000);
        clickText("飞行模式");
        sleep(1000);
        isConnect = laoleng.http.isConnectAble();
        sleep(2000);
        if (!isConnect) {
            homes();
            break;
        }
    }
    return true;
}

/**
 * 切换用户（调用xx抹机神器切换用户环境）
 */
function switch_user_environment() {
    //1、打开XX抹机系统
    while (true) {
        if (utils.isAppExist(enumId.xxmj_pkgName)) {
            utils.openApp(enumId.xxmj_pkgName);
        } else {
            utils.openAppByName("xx抹机神器");
        }
        sleep(1000);
        if (checkXXmjIsopen()) {
            logd("打开抹机神器成功");
            break;
        }
    }
    if (isUsefulAccount == 0) {
        xxmjRemark();
        sleep(2000);
    }
    while (true) {
        let node1 = id(enumId.xxmj_switchEnvrion);
        click(node1);
        sleep(3000);
        if (has(id(enumId.xxmj_switchNextOne))) {
            break;
        }
    }
    let nextNode = id(enumId.xxmj_switchNextOne).getOneNodeInfo(2000);
    if (nextNode) {
        logd("切换下一个用户:" + nextNode.click());
        while (true) {
            sleep(5 * 1000);
            let node = id(enumId.xxmj_currentIcon);
            if (has(node)) {
                logd("切换用户结束");
                break;
            }
            logd("加载中....");
            sleep(1000);
            let pkg = getRunningPkg();
            if (pkg != enumId.xxmj_pkgName) {
                laoleng.app.cleanApp("com.android.settings");
                sleep(500);
                utils.openApp(enumId.xxmj_pkgName);
            }
        }
        openXHS();
    }
    isUsefulAccount = 1;
    return true;
}

/**
 * 判断小红书是否在首页
 * @returns {bool|布尔型}
 */
function xhsIsLoginHome() {
    sleep(500);
    return has(id(enumId.homePage_fabuIcon)) && has(text("首页"));
}

/**
 * 当前页是否在首页-发现页
 */
function checkDiscoverAndHomePage() {
    let discover = text("发现").getOneNodeInfo(1000);
    if (discover == null) {
        return false;
    }
    // logd(JSON.stringify(discover));
    let firstPage = text("首页").index(0).getOneNodeInfo(1000);
    if (firstPage == null) {
        return false;
    }
    // logd(JSON.stringify(firstPage));
    return discover.selected && firstPage.selected;
}


/**
 @description 通过包名启动应用。如果该包名对应的应用不存在，则返回false；否则返回true。
 @version     20201125
 @author      飞云<283054503@qq.com>
 @param       packageName {string} :应用包名
 @param       delay {number} :启动后等待时长，单位毫秒。默认5000
 @param       startNum {number} :重试次数。默认3
 @return      {boolean}:返回是否成功
 */
function launch(packageName, delay, startNum) {
    let result = false;
    if (!delay) {
        delay = 5000;
    }
    if (!startNum) {
        startNum = 3;
    }
    if (utils.isAppExist(packageName)) {
        if (getRunningPkg() === packageName) {
            logd('应用已经在前台');
            result = true;
        } else {
            logd('启动应用...');

            let selectors = text('允许');
            let num = 0;
            while (num < startNum) {
                if (getRunningPkg() === packageName) {
                    logi('启动成功');
                    result = true;
                    break;
                } else if (has(selectors)) {
                    let node = selectors.getOneNodeInfo(1000);
                    if (node) {
                        node.click()
                    }
                } else {
                    utils.openApp(packageName);
                    sleep(delay);
                    num++;
                }
            }
        }
    } else {
        loge('应用未安装');
    }
    if (result) {
        logd('应用版本号：' + utils.getAppVersionName(packageName));
    }
    return result;
};